<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\util;

use app\index\model\OrderCommodity;
use app\index\model\PresellCommodity;
use app\index\service\InventoryService;
use think\Exception;

class Inventory
{

    public static function sub($orderId)
    {
        $orderCommodity = OrderCommodity::where(['order_id' => $orderId])->select();
        foreach ($orderCommodity as $commodity) {
            $inventoryService = new InventoryService($commodity['commodity_id']);
            $inventoryType = $inventoryService->getInventoryType();
            if ($inventoryType == 3) {
                try {
                    $inventoryService->subInventoryByCount($commodity['count'], $commodity['sku_id']);
                    // 预售
                    if ($commodity['pc_id'] > 0) {
                        PresellCommodity::decStock($commodity['pc_id'], $commodity['count'], $commodity['sku_id']);
                    }
                } catch (Exception $e) {
                    OrderCommodity::where(['id' => $commodity['id']])->update(['is_sell_out' => 1]);
                }
            }
        }
    }
    public static function getLevelPrice($data){
        global $user;
        if (empty($data['level_price']))return null;
        $value = json_decode($data['level_price'],true);
        if (empty($value))return null;
        if(!empty($user['level'])) {
            if ($value['type'] == 1) {
                foreach ($value['price'] AS $key => $item){
                    if($item['level'] == $user['level']){
                        if ($item['type'] == 1)
                            return (float)bcmul((string)$item['price'],'1',2);
                        else
                            return (float)bcmul((string)$item['price'],(string)$data['sell_price'],2);
                    }
                }
            }
            return null;
        }else{
            return null;
        }
    }
}